<template>
	<view class="main">
		<form @submit="onSubmit" report-submit>
			<view class="container-top">
				<!-- 封面 -->
				<view class="container-top-imageview">
					<view class="image-list">
						<!-- 图片列表 -->
						<view class="image-preview" v-for="(item,index) in imageList">
							<text class="image-delete iconfont icon-shanchu" @tap="deleteImage" :data-index="index" :data-image-index="index"></text>
							<image class="images" mode="aspectFill" :src="item"></image>
						</view>
						<!-- 上传图片 -->
						<form v-if="imageList.length < 1" @submit="chooseImage" report-submit="true">
							<button class="btn-normal" form-type="submit">
								<view class="image-picker dis-flex flex-dir-column flex-x-center flex-y-center">
									<text class="choose__icon iconfont icon-tubiao_xiangji"></text>
									<text class="choose__text">上传封面</text>
								</view>
							</button>
						</form>
					</view>
				</view>


				<view class="container-top-input">
					<input class="uni-input" name="title" placeholder="填写标题会获得很多赞哦~" placeholder-style="color:#b8b8b8" />
				</view>


				<view class="toolbar" @touchend.stop="format" :style="'bottom: ' + (isIOS ? keyboardHeight : 0) + 'px'">

					<i class="iconfont icon-charutupian" @touchend.stop="insertImage"></i>
					<view :class="formats.bold ? 'ql-active' : ''" class="iconfont icon-zitijiacu" data-name="bold"></view>
					<view :class="'iconfont icon-format-header-1 ' + (formats.header === 1 ? 'ql-active' : '')" data-name="header"
					 :data-value="1"></view>
					<view :class="'iconfont icon-juzhongduiqi ' + (formats.align === 'center' ? 'ql-active' : '')" data-name="align"
					 data-value="center"></view>
					<view :class="'iconfont icon-text_color ' + (formats.color === fontColor ? 'ql-active' : '')" data-name="color"
					 :data-value="fontColor" @tap="open"></view>
					<i class="iconfont icon-date" @tap="insertDate"></i>
					<i class="iconfont icon-preview" @tap="store" id="2"></i>
				</view>

				<t-color-picker ref="colorPicker" :color="color" @confirm="confirm" @cancel="cancel"></t-color-picker>

			</view>

			<view class="container">
				<editor id="editor" show-img-size :read-only="isEdit" show-img-resize show-img-toolbar class="ql-container"
				 :placeholder="placeholder" @statuschange="onStatusChange" @ready="onEditorReady">
				</editor>
			</view>


			<!-- 位置信息 -->
			<view class="row-textarea dis-flex" @tap="onClickLocation">
				<uni-icon type="location" size="22"></uni-icon>
				<text class="row-textarea-text">{{m_location}}</text>
				<view class="menus-item__right flex-box dis-flex flex-x-end flex-y-center">
					<text class="menus-item__right_icon iconfont icon-xiangyoujiantou f-26 col-7"></text>
				</view>
			</view>





			<button class="otherSendBtn btn-normal" form-type="submit">
				<view class="flow-btn f-32">提 交</view>
			</button>


		</form>
	</view>
</template>

<script>
	import tColorPicke from '@/components/t-color-picker/t-color-picker.vue';
	var _self;
	export default {
		components: {
			't-color-picker': tColorPicke
		},
		data() {
			return {
				imageList: [],
				tempFilesList: [],
				m_location: '选择位置',
				color: {
					r: 255,
					g: 0,
					b: 0,
					a: 0.6
				},
				isEdit: false,
				fontColor: '#000',
				formats: {},
				readOnly: false,
				placeholder: '开始输入...',
				editorHeight: 300,
				keyboardHeight: 0,
				isIOS: false
			};
		},
		onLoad() {
			_self = this;
		},

		methods: {

			onSubmit: function(e) {


				let _this = this;
				let _e = e;
				_this.editorCtx.getContents({
					success: function(res) {
						if (!_e.detail.value.title) {
							_this.showError('标题不能为空！');
							return false;
						}
						let html = res.html;
						// 统计图片数量
						let imagesLength = _this.imageList.length;
						if (imagesLength == 0) {
							_this.showError('请选择图片！');
							return false;
						}

						uni.showLoading({
							title: '正在处理...',
							mask: true
						});

						let location = _this.m_location;
						if (location == '选择位置') {
							location = '';
						}

						_this._post_form('social.social/add', {
							content: html,
							title: _e.detail.value.title,
							city: location
						}, (result) => {
							// console.log(result);
							if (result.code === 1) {
								_this.onSendSubmit(_e, result.data);
							} else {
								_this.showError('验证失败！');
							}
						});
					},
					fail: function() {
						_this.showError('编辑失败！');
						return false;
					}
				});

			},
			/**
			 * 表单提交请求
			 */
			onSendSubmit: function(e, data) {
				let _this = this;

				let imagesLength = _this.imageList.length;
				// 文件上传
				let i = 0;

				this.imageList.forEach(function(filePath, fileKey) {
					// console.log('图片开始上传');

					uni.uploadFile({
						url: _this.api_root + 'social.social/upload',
						filePath: filePath,
						name: 'image',
						formData: {
							s_id: data,
							wxapp_id: _this.siteInfo.wxapp_id,
							token: uni.getStorageSync('token'),
						},
						success: function(res) {},
						complete: function(res) {
							console.log(JSON.stringify(res));
							i++;
							if (imagesLength === i) {
								// 所有文件上传完成
								// 执行回调函数
								uni.hideLoading();

								_this.showModal('动态发送成功！', function(res) {

									let imageList = [];
									_this.setData({
										imageList: imageList,
										textarea: ''
									});
									uni.switchTab({
										url: "../pubu/pubu",
									});
								});
								// uni.showModal({
								// 	title: '提示',
								// 	content: '动态发送成功！',

								// 	success: function(res) {

								// 		let imageList = [];
								// 		_this.setData({
								// 			imageList:imageList,
								// 			textarea: ''
								// 		});
								// 		uni.switchTab({
								// 			url: "../pubu/pubu",
								// 		});
								// 	}
								// });
							}
						}
					});
				});
			},
			/**
			 * 选择位置
			 */
			onClickLocation(e) {
				let _this = this;
				uni.chooseLocation({
					success: function(res) {
						// console.log('位置名称：' + res.name);
						// console.log('详细地址：' + res.address);
						// console.log('纬度：' + res.latitude);
						// console.log('经度：' + res.longitude);
						// _this.m_location = res.name

						_this.setData({
							m_location: res.address
						});
					}
				})
			},
			/**
			 * 选择图片
			 */
			chooseImage: function(e) {
				let _this = this,
					index = 0,
					imageList = _this.imageList;

				let mode = 1; //裁剪   1原图
				if (mode == 0) {
					// 记录formId
					_this.saveFormId(e.detail.formId);

					let listCount = 0;
					if (imageList.length > 0) {
						listCount = 2;
					}
					_this.$refs.avatar.fChooseImg(index, {
						maskListIndex: listCount,
					});
				} else {
					// 选择图片
					uni.chooseImage({
						count: 1,
						sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
						sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
						success: function(res) {
							
							_self.showLoading()
							// #ifdef APP-PLUS
							if (res.tempFiles[0].size > 504800){
								uni.getImageInfo({
									src: res.tempFilePaths[0],
									success: function (image) {
										if (res.tempFiles[0].size > 504800){
											var role = 0
											console.log(image)
											if (image.orientation == 'right'){
												role = 90
											}
											
											
											plus.zip.compressImage({
													src: res.tempFilePaths[0],
													dst: "_doc/a.jpg",
													quality: 50,
													width:"40%",
													height:"40%",
													overwrite:true,
													format:'jpg',
													rotate:role,
												},
												function(event) {
													console.log("Compress success!");
													var target = event.target; // 压缩转换后的图片url路径，以"file://"开头
													var size = event.size; // 压缩转换后图片的大小，单位为字节（Byte）
													var width = event.width; // 压缩转换后图片的实际宽度，单位为px
													var height = event.height; // 压缩转换后图片的实际高度，单位为px
													
													_this.tempFilesList.push(target);
													
													
													_this.setData({
														imageList: imageList.concat(target),
													});
													
													_self.hideLoading()
													
													
													
												},
												function(error) {console.log("Compress error!");
													_self.hideLoading()
												}
											)
											
										}
									}
								});
									
							}else{
								_this.tempFilesList.push(res.tempFiles);

								_this.setData({
									imageList: imageList.concat(res.tempFilePaths),
								});
								
								_self.hideLoading()
							}
							return;
							//  #endif
							
							_this.tempFilesList.push(res.tempFiles);

							_this.setData({
								imageList: imageList.concat(res.tempFilePaths),
							});
						}
					});
				}
			},
			/**
			 * 删除图片
			 */
			deleteImage: function(e) {
				let dataset = e.currentTarget.dataset,
					imageList = this.imageList;
				imageList.splice(dataset.imageIndex, 1);
				this.setData({
					imageList
				});

				this.tempFilesList.splice(dataset.imageIndex, 1);


			},
			cancel() {
				this.isEdit = false;
			},
			open() {
				this.$refs.colorPicker.open();
				this.isEdit = true;
				// uni.hideKeyboard();
			},
			hideKey() {
				uni.hideKeyboard();
			},
			async confirm(e) {
				this.isEdit = false;
				this.fontColor = await e.hex;
				this.onStatusChange({
					detail: {
						color: e.hex
					}
				});
				this.$forceUpdate();
			},
			readOnlyChange() {
				this.readOnly = !this.readOnly
			},
			onEditorReady() {
				uni.createSelectorQuery().select('#editor').context(function(res) {
					_self.editorCtx = res.context;
				}).exec();
			},
			undo() {
				this.editorCtx.undo();
			},

			redo() {
				this.editorCtx.redo();
			},

			blur() {
				this.editorCtx.blur();
			},

			format(e) {
				// this.hideKey();
				let {
					name,
					value
				} = e.target.dataset;

				console.log(e)
				if (!name) return;

				this.editorCtx.format(name, value);
			},

			onStatusChange(e) {
				this.formats = e.detail;
			},

			insertDivider() {
				this.editorCtx.insertDivider({
					success: function() {
						console.log('insert divider success');
					}
				});
			},

			store(e) {
				this.editorCtx.getContents({
					success: function(res) {
						uni.navigateTo({
							url: `./preview?rich=${encodeURIComponent(res.html)}`
						});
					}
				});
			},

			clear() {
				this.editorCtx.clear({
					success: function(res) {
						console.log("clear success");
					}
				});
			},

			removeFormat() {
				this.editorCtx.removeFormat();
			},

			insertDate() {
				const date = new Date();
				const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
				this.editorCtx.insertText({
					text: formatDate
				});
			},
			uploadFile(filePath){
				var _this = this;
				var _filePath = filePath;
				uni.uploadFile({
					url: _this.api_root + 'social.social/uploadeditor', 
					filePath: _filePath,
					name: 'image',
					header: {
						'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
					},
					formData: {
						wxapp_id: _this.siteInfo.wxapp_id,
						token: uni.getStorageSync('token'),
					},
					success: function(resFile) {
						let v= JSON.parse(resFile.data)
							console.log(resFile)
						if (resFile.statusCode ==200){
							let a = _this.siteInfo.siteroot + 'uploads/' + v[0] + '/' + v[1]
							_self.editorCtx.insertImage({
								src: _this.siteInfo.siteroot + 'uploads/' + v[0] + '/' + v[1],
								data: {
									id: 'abcd',
									role: 'god'
								},
								width: '100%',
								
								success: function() {
									
									_self.hideLoading()
								}
							});
						}
					}
				});
			},
			insertImage() {
				let _this = this;
				// const that = this;
				uni.chooseImage({
					count: 1,
					sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: function(res) {
						console.log(res);
						
						_self.showLoading()
						// #ifdef APP-PLUS
						if (res.tempFiles[0].size > 504800){
							var role = 0;
							uni.getImageInfo({
								src: res.tempFilePaths[0],
								success: function (image) {
									console.log(image)
									if (image.orientation == 'right'){
										role = 90
									}else{
										role = 0
									}
									
									plus.zip.compressImage({
											src: res.tempFilePaths[0],
											dst: "_doc/b.jpg",
											quality: 50,
											width:"40%",
											height:"40%",
											overwrite:true,
											format:'jpg',
											rotate:role,
										},
										function(event) {
											console.log("Compress success!");
											var target = event.target; // 压缩转换后的图片url路径，以"file://"开头
											var size = event.size; // 压缩转换后图片的大小，单位为字节（Byte）
											var width = event.width; // 压缩转换后图片的实际宽度，单位为px
											var height = event.height; // 压缩转换后图片的实际高度，单位为px
											_this.uploadFile(target);
											
											console.log('图片转化后的大小：'+size)
											
											
											
										},
										function(error) {_this.showError(error)
										}
									)
								}
							});
							
							
								
						}else{
							_this.uploadFile(res.tempFilePaths[0]);
						}
						return;
						//  #endif
						
						_this.uploadFile(res.tempFilePaths[0]);




					}
				});
			}
		}
	};
</script>
<style>
	@import "../../utils/editpriconfont.css";

	page {
		height: 100%;
	}

	.main {
		background: #ffffff;
		width: 100%;
		height: 100%;
	}

	.container-top {
		width: 100%;
	}

	.container-top .container-top-input {
		display: flex;
		flex-direction: row;
		padding: 20upx 25upx;
	}

	.container-top .container-top-input .uni-input {
		border-bottom: 1upx solid #dcdcdc;
		width: 100%;
	}

	.container-top-imageview {
		display: flex;
		flex-direction: row;
		padding: 20upx 0upx;
	}



	.image-list {
		padding: 0upx 25upx;
	}

	.image-list:after {
		clear: both;
		content: " ";
		display: table;
	}

	.image-list .image-preview {
		margin: 15upx 30upx 15upx 0;
		float: left;
	}

	.image-list .image-preview .images {
		width: 152upx;
		height: 152upx;
	}

	.image-list .image-preview:nth-child(4n+0) {
		margin-right: 0;
	}

	.image-list .image-preview {
		position: relative;
	}

	.image-list .image-preview .image-delete {
		position: absolute;
		top: -15rpx;
		right: -15rpx;
		height: 42rpx;
		width: 42rpx;
		line-height: 42rpx;
		background: rgba(0, 0, 0, 0.64);
		border-radius: 50%;
		color: #fff;
		font-weight: bolder;
		font-size: 22upx;
		z-index: 10;
		text-align: center;
	}

	.row-textarea {
		padding: 25upx 20upx;
		border-top: 1upx solid #dcdcdc;
	}

	.row-textarea .row-textarea-text {
		color: #b8b8b8;
	}

	.row-textarea .menus-item__right .menus-item__right_icon {
		width: 25upx !important;
	}

	.image-picker {
		width: 150upx;
		height: 150upx;
		border: 1upx dashed #ccc;
		color: #ccc;
	}

	.btn-normal .image-picker .choose__icon {
		font-size: 40upx;
		margin-bottom: 6upx;
		width: 32upx;
	}

	.iconfont1 {
		font-size: 150upx;
		color: #ccc;
		text-align: center;
		display: block;
		margin-bottom: 12upx;
	}

	.container-top-imageview .title {
		padding: 0upx 25upx;
	}

	.choose__text {
		font-size: 22rpx;
	}


	.container {
		/* position: absolute; */
		/* top: 620px; */
		/* left: 0; */
		/* width: 100%; */
		height: 450upx;
		padding: 20px 10px 20px 10px;


	}

	.ql-container {
		box-sizing: border-box;
		width: 100%;
		height: 100%;
		font-size: 16px;
		line-height: 1.5;
		overflow: auto;
	}

	.ql-active {
		color: #22C704;
	}

	.iconfont {
		display: inline-block;
		width: 32px;
		height: 30px;
		cursor: pointer;
		font-size: 20px;
	}

	.toolbar {
		box-sizing: border-box;
		padding: 10px;
		/* height: 130px; */
		/* width: 100%; */
		/* position: fixed; */
		/* left: 0; */
		/* margin-bottom: 100upx; */

		background: #fff;
		/* right: 100%; */
		display: flex;
		flex-wrap: wrap;
		text-align: center;
	}

	.otherSendBtn {
		width: 100%;
		text-align: center;
		color: #555555;
		font-size: 28upx;
		margin: auto;
		line-height: 80upx;
		position: fixed;
		justify-content: center;
		bottom: 0upx;
	}

	.border-bottom {
		border-bottom-width: 1upx;
		border-color: #dcdcdc;
		border-bottom-style: solid;
	}
</style>
